package miaodiyun

import (
	"gitee.com/yxd1990/golang-common/myType"
	"gitee.com/yxd1990/golang-common/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
)

var accountSid string
var authToken string

func init() {
	authToken = beego.AppConfig.DefaultString("authToken", "df06dedbfea2640733a9d9ee10239bd9")
	accountSid = beego.AppConfig.DefaultString("accountSid", "f19085a30288ecf470cb70cf558043a5")
}

type SmsSendResult struct {
	RespCode string            `json:"respCode"`
	RespDesc string            `json:"respDesc"`
	SmsId    string            `json:"smsId"`
	//FailList map[string]string `json:"failList"`
}

func SendSmsTemplateMessage(templateid string, telephone string) (result *SmsSendResult,err error) {
	url := "https://openapi.miaodiyun.com/distributor/sendSMS"
	req := httplib.Post(url)
	req.Param("respDataType", "JSON")
	req.Param("accountSid", accountSid)
	req.Param("templateid", templateid)
	req.Param("to", telephone)
	timestamp := fmt.Sprintf("%d", myType.UnixSeconds())
	req.Param("timestamp", timestamp)
	req.Param("sig", utils.GetMd5Value(accountSid+authToken+timestamp))
	var data []byte
	req.Debug(true)
	data, err = req.Bytes()
	logs.Info("SendSmsTemplateMessage request :%s", string(req.DumpRequest()))
	result = &SmsSendResult{}
	if err == nil {
		logs.Info("SendSmsTemplateMessage to %s response : %s", telephone, string(data))
		err = json.Unmarshal(data, result)
	} else {
		logs.Error("SendSmsTemplateMessage error:%s", telephone, err)
	}
	return
}
